<script setup lang="ts">
import {ref} from "vue"
const {text=new Array(100).fill('\x00').join(''),start = 0} = defineProps<{text?:string,start?:number}>()



const isNone = (s:string) => {
    let r = /^0/.test(s);
    // switch(s){
    //     case "00":r = true;break;
    // }

    return r;
}

const hex2char = (n:string) => {
    return isNone(n) ? '.' : String.fromCharCode(parseInt(n,16));
}

const char2hex = (s:string) => {
    const r = s.charCodeAt(0).toString(16).toUpperCase()
    return r.length == 1 ? `0${r}` : r;
}

const calcPos = (n:number) => {
    const s = Number(n * 16 + start).toString(16).toUpperCase();
    return s.padStart(8,'0')
}
const ts = text.split('').map(s => char2hex(s))


const hoverOffset = ref(-1)
const onHover = (i?:number) => {
    hoverOffset.value = i == undefined ? -1 : i;
}
</script>

<template>
    <div class="hex-content w-full h-full overflow-auto pr-6 flex gap-1em text-14px lh-20px c-#333 box-border">
        <div class="bg-#eee p-x-6px">
            <template v-for="i in Math.ceil(ts.join('').length / 32)">
                <div class="" :data-offset="start + (i - 1) * 16">{{ calcPos(i-1) }}</div>
            </template>
        </div>
        <div class="grid grid-cols-16">
            <template v-for="(t,i) in ts">
                <span :data-offset="i + start" :class="[' p-x-4px cursor-default text-center',hoverOffset == i ? 'bg-#ddd' : '']" @mouseenter="onHover(i)" @mouseleave="onHover()"  >{{ t.substring(0,2) }}</span>
                <span v-if="t.length == 4" :data-offset="i + start" :class="[' p-x-4px cursor-default text-center',hoverOffset == i ? 'bg-#ddd' : '']" @mouseenter="onHover(i)" @mouseleave="onHover()"  >{{ t.substring(2) }}</span>
            </template>
        </div>
        <div class="_string grid grid-cols-16 text-center">
            <template v-for="(t,i) in ts">
                <span :data-offset="i + start" :class="['p-x-1px cursor-default',hoverOffset == i ? 'bg-#ddd' : '',{'c-#aaa':isNone(t)}]" @mouseenter="onHover(i)" @mouseleave="onHover()" >{{ hex2char(t) }}</span>
                <span v-if="t.length == 4" :class="['p-x-1px cursor-default c-#eee',hoverOffset == i ? 'bg-#ddd' : '']" @mouseenter="onHover(i)" @mouseleave="onHover()">.</span>
            </template>
        </div>
    </div>
</template>

<style scoped>
.hex-content {
    font-family:  Consolas, Menlo, "PT Mono", "Liberation Mono", monospace;
}
</style>